function bindTableSorter( $pattern ){	
	$($pattern).tablesorter({ 
        headers: { 
            0: { 
                sorter: false 
            }
        }, 
        widgets: ['zebra']
    }); 
}

function bindSelectAll(){	
	$("#selectAll").click(function(){			
		$("input.item", $(this).parent().parent().parent().parent()).attr("checked", $(this).attr("checked"));
	});
}

function ping( time ){		
	$.ajax({
		   type: "POST",
		   url: "/negocios/ping",
		   cache: false,
		   success: notifyPedido
	});	
		
	setTimeout( "ping( "+time+" )", time )	
		
}

function ring(){
	$.sound.play("/sounds/telephone-ring-4.mp3", {timeout: 5000});
}

function testRing(){
	$(".testRing").click(ring);
}

function setPoints2Form( poly ){

	polygon = poly;
	input = document.getElementById("coordenadas");
	val = new Array();
	n = poly.getVertexCount(); 
	
	for (i=0; i<n; i++){
		v = poly.getVertex( i );
		val[i] = v.lat() + ' ' + v.lng();
	}
	
	input.value = val.join(",");	
}

function bindZonaMap() {
	var $boxy;
	
	$("#coordenadas").bind('click.init',
	function(e){
		
		$("#map").css("width", $(window).width() * 0.9 ).css("height", $(window).height() * 0.8).css("background", "#fff url(/img/ajax-loading.gif) no-repeat scroll center center");
		
		if (GBrowserIsCompatible()) {
			  
		    map = new GMap2(document.getElementById("map"));
		    map.setCenter(new GLatLng($center.lat, $center.lon), 15);
		    map.addControl(new GSmallMapControl());
		    map.addControl(new GMapTypeControl());
		    map.clearOverlays();
		    addZona( );
		    addMarker( $center.lat, $center.lon );
		}
		
		$boxy = new Boxy( "#map", {
			title: "Zona de entrega",
			modal: true,
			closeable: true
		});
		
		$("#coordenadas").unbind('click.init');
		return false;
	});
	
		
	$("#coordenadas").click(function(){
		$boxy.show();
	});
	
}

function bindZonasMap() {
	var $boxy;
	
	$("#maptrigger").bind('click.init',
	function(e){
				
		$("#map").css("width", $(window).width() * 0.9 ).css("height", $(window).height() * 0.8).css("background", "#fff url(/img/ajax-loading.gif) no-repeat scroll center center");
				
	  if (GBrowserIsCompatible()) {
		  
	    map = new GMap2(document.getElementById("map"));
	    map.setCenter(new GLatLng($center.lat, $center.lon), 15);
	    map.addControl(new GSmallMapControl());
	    map.addControl(new GMapTypeControl());
	    map.clearOverlays();
	    addZonas( );
	    addMarker( $center.lat, $center.lon );
	  }
	  
	  	$boxy = new Boxy( "#map", {
			title: "Zona de entrega",
			modal: true,
			closeable: true
		});
		
		$("#maptrigger").unbind('click.init');
		return false;
	  
	});
	
	$("#maptrigger").click(function(){
		$boxy.show();
	});
	
}

function addZona(  ){
	
	var $points = new Array();
	var $create = true;

	if ( typeof $area == 'object' ){					
		for ( p in  $area.coordinates){	
			point = $area.coordinates[p];
			$points[p] = new GLatLng(point.lat, point.lon);	
		}		

		$create = false;		
	}
	
	var poly = new GPolygon($points, "#ff0000", 1, 0.7, "#ff0000", 0.2);
	
	poly.enableEditing({onEvent: "mouseover"});
	poly.disableEditing({onEvent: "mouseout"});
	
	if ( $create ){		
		poly.enableDrawing([]);

		GEvent.addListener(poly, "endline", function() {
			bindDelete(poly);
			bindCoord(poly); 
		});
		
	} else {
		bindDelete(poly);
		bindCoord(poly);
	}	
	
	map.addOverlay(poly);
			
}

function addZonas(  ){
	
	colors = new Array("#9ACD32","#4B0082","#8A2BE2","#808000","#B0E0E6","#BC8F8F","#A52A2A","#C0C0C0","#1E90FF","#8FBC8F")
	
	
	for ( a in  $areas){	
	
		area = $areas[a];
		
		$points = new Array();
	
		for ( p in  area.coordinates){	
			coors = area.coordinates[p];
			$points[p] = new GLatLng(coors.lat, coors.lon);	
		}		
				
		map.addOverlay(
				new GPolygon($points, colors[a], 3, 0.7, colors[a], 0.3)
		);
	}
}

function addMarker( lat, lon ){
	map.addOverlay(new GMarker(new GLatLng(lat, lon)));
}



function bindDelete(poly){
	GEvent.addListener(poly, "click", function(latlng, index) {
      if (typeof index == "number") {
        poly.deleteVertex(index);
      } 
    });	
}

function bindCoord(poly){
	GEvent.addListener(poly, "endline", function() {
		setPoints2Form( poly );
	});

	GEvent.addListener(poly, "lineupdated", function(){
		setPoints2Form( poly );		
	});
}






/* Paginator */

var $paginatorOrders	= null;
var $paginatorContainer	= ".tablesorter";
var $paginatorLoading	= null;
var $paginatorCallback	= null;

function bindPaginate( $url ){
	var $params = {};
	
	$('[class^="sort"]').click(function(){
	
		$params = paginatorGetOrder( $params, $(this));
		$params = paginatorGetFilters( $params );
		
		paginatorGetData( $url, $params);	
		
	});
	
	$(".paginatorPage").click(function(){
			
		if ( $(this).hasClass('disabled')){
			return;						
		}
		
		if ( $(this).hasClass('prev')){
			$params.page = $(this).parent().find('.currentPage').text() - 1;						
		}else if ( $(this).hasClass('next') ){
			$params.page = parseInt($(this).parent().find('.currentPage').text()) + 1;						
		}
		else {
			$params.page = $(this).text();
		}
		
		$params = paginatorGetOrder( $params );
		$params = paginatorGetFilters( $params );
		
		paginatorGetData( $url, $params);
		
	});
	
	$(".paginatorFilters button, .paginatorFilters .button").unbind('click');
	
	$(".paginatorFilters button, .paginatorFilters .button").click(function(){
		
		$params = paginatorGetFilters( $params );
		
		$params.page = 1;
		
		paginatorGetData( $url, $params);
		
	});
	
	bindSelectAll();
	
	if ( $paginatorCallback ){
		$paginatorCallback();
	}

}

function paginatorGetData( $url, $params ){
	$( $paginatorContainer ).fadeOut( 500 );

	$.ajax({
		url:$url,
		type:"post",
		cache: false,
		data: $params,
		success: function( $html ){
			paginatorSetData( $url, $html );
		}
	});
}
function paginatorSetData( $url, $html ){
	
	$html = $($html);
	$html.hide();
	
	$( $paginatorContainer ).replaceWith( $html );
	$( $paginatorContainer ).fadeIn( 1000 );
	bindPaginate( $url );
}


function paginatorGetOrder( $params, $el ){
	var $element;
	
	if ( $el == null ){
		
		$('[class^="sortASC"], [class^="sortDESC"]').each(function(){
			$element = $(this);			
		});
	} else {
		$element = $el;
	}
	
	if ( $element == null ){
		return $params;
	}
	
	var $index = $("th").index( $element );
	var $name  = $paginatorOrders[$index];
	var $dir;
	
	if( $el ){
		if ( $el.hasClass("sortASC") ){
			$dir = "DESC"; 		
		}else{
			$dir = "ASC";
		}
	} else {
		$dir = $element.hasClass("sortASC") ? "ASC" : "DESC";
	}

	$params.order = $name + ' ' + $dir;
	return $params;
}

function paginatorGetFilters( $params ){
	$(".paginatorFilter").each(function(){
		
		$val = $(this).val();
		
		if ( $val != null ){
			
			$params[$(this).attr("name")] = $val;
			
		}
		
		
	});

//	console.log($params);
	
	return $params;
}


function refresh(){
	window.location.replace( window.location.href );
}

function notifyPedido( n ){
	if ( ! isNaN( n ) && n > 0 ){
		
		$el = $("#menu ul li:first a");
		$text = _t("nerOrders");

		$el.qtip({ 
			style: { name: 'red', tip: true }, 
			content: { text: $text },
			show: { ready: true },
			hide: { when: { target: $el, event: 'click'} },
			position: { corner: { tooltip: 'bottomMiddle', target: 'topMiddle' } }				
		});
		
		ring();
	}
}

function resetPromoProductos( $todo ){
	
	if($todo ===false){
		$("#productosSelect li input:checked").attr('checked', false);		
	} else {
		$( "#addPromoItem form" ).reset();
	}
	
	$("#productosSelectAll").attr('checked', true);
}

function initPromoProductos(){
	
//	
	
	var $promoBoxy;
	var $html = $("#addPromoItemContainer").html();
	
	$("#addPromoItemContainer").remove();
	
	$("#addPromoItem").remove();
	//trigger open boxy
	$( "#agregar" ).click(function(){
		
		resetPromoProductos();
		
		$promoBoxy = new Boxy( $html,{
			title: "Crear / Modificar Promoción",
			height: 300,
			width: 600,
			modal: false,
			show: true,
			closeable: true,
			unloadOnHide:true,
			afterHide: resetPromoProductos
		});
		
		$(".boxy-inner #addPromoItem").css('height', $(window).height() - 200).css('overflow', 'scroll');
		
		$promoBoxy.center();
		
		promoProductExplain();
		bindCategoria( $promoBoxy );
		bindPromoProductChange();
		
		$(".boxy-inner #cantidad").unbind("change");
		
		$(".boxy-inner #cantidad").change(function(){
			promoProductExplain();
		})
		
		$( ".boxy-inner #addPromoItem #itemAdd" ).click(function(){
		
			$cantidad = parseFloat($(".boxy-inner #cantidad").val());
			
			if ( isNaN($cantidad) || $cantidad==0 ){
				
				Boxy.alert("Por favor indique una cantidad");
				return;
			}
			
			$categoria = parseInt($(".boxy-inner #categoria").val());
			
			if ( isNaN($categoria) || $categoria==0 ){
				
				alert("Por favor indique una categoria");
				return;
			}
	
			addItem();
			$promoBoxy.hide();
			return false;
		});
		
		// trigger close boxy
		$( ".boxy-inner #addPromoItem #itemCancel" ).click(function(){
			$promoBoxy.hide();
			return false;
		});
		
		
		return false;
	});
	
}

function bindPromoProductChange(){
	
	$(".boxy-inner #productosSelectAll").change(function(){
		
		if ( $(this).attr('checked') == false){
			$(this).attr('checked', true);
		} else {
			$(".boxy-inner #productosSelect li input:checked").attr('checked', false);
		}
		
		promoProductExplain();
		
	});
	
	$(".boxy-inner #productosSelect li input").change(function(){
	
		$list = $(".boxy-inner #productosSelect li input:checked");
		
		if ( $list.length == 0){
			$(".boxy-inner #productosSelectAll").attr('checked', true);
		} else {
			$(".boxy-inner #productosSelectAll").attr('checked', false);
		}
		
		promoProductExplain();
		
	});
}

function promoProductExplain(){
	
	$(".boxy-inner #productosSelectExplain").show();
	
	$cantidad = parseFloat($(".boxy-inner #cantidad").val());
	$categoria = $(".boxy-inner #categoria option:selected").text();
	
	if( isNaN($cantidad) || $categoria==""){
		$(".boxy-inner #productosSelectExplain").hide();
	}

	if ( $(".boxy-inner #productosSelectAll").attr('checked')){
		
		$text = $cantidad + _t("promoProductExplainText1") + $categoria;
		
	} else {
		
		$list = $(".boxy-inner #productosSelect li input:checked");
		
		if ( $list.length == 1){
			
			$text = $cantidad + " x " + $categoria + ": " + $list.first().parent().find("label").text();
			
		} else {
			$text = $cantidad + _t("promoProductExplainText2");
			
			$list.each( function(){	
				$text+= $(this).parent().find("label").text() + ", ";
			});
			
			$text = $text.substr(0, ($text.length - 2));
			
		}
	}
	
	$(".boxy-inner #productosSelectExplain").text( $text );
}

function bindCategoria( $promoBoxy ){
	$(".boxy-inner #categoria").change(function(){
		
		var $idCategoria = $(this).val();
		
		$(".boxy-inner #productosSelect li").hide();
		$(".boxy-inner #productosSelect li input").attr('checked', false);
		
		if ($idCategoria != 0){
			$(".boxy-inner #productosSelect").show();
			$(".boxy-inner #productosSelect li[class=categoria-"+$idCategoria+"]").show();
			
		} 
		
		$promoBoxy.center();
		resetPromoProductos( false );
		promoProductExplain();
	});
}

function addItem()
{
	$idCategoria = $(".boxy-inner #categoria").val();
	$cantidad = $(".boxy-inner #cantidad").val();

	
	var activos = $(".boxy-inner #productosSelect li[class=categoria-"+$idCategoria+"] input:checked");
	
	var $condicion;
	var $type;
	var $id;
	
	if (activos.length == 0 ){
		$condicion = $(".boxy-inner #categoria option[value="+$idCategoria+"]").text();
		$id = $idCategoria;
		$type = "categoria";
		
	} else if (activos.length == 1 ){
		$condicion = $(".boxy-inner #categoria option[value="+$idCategoria+"]").text();
		$condicion+= ": " + activos.parent().find("label").text();
		$id = activos.val();
		$type = "producto";
		
	} else {
		
		$condicion = $(".boxy-inner #categoria option[value="+$idCategoria+"]").text() + ": " ;
		
		$type = "productos";
		$ids = new Array();
		activos.each(function(i){
			
			$condicion+= $(this).parent().find("label").text() + " o " ;
			
			$ids[i]= $(this).val();
		});		
		
		$id = $ids.join(",");
		
	}
	 
	$("#Productos tbody").append("<tr><td><input type='checkbox' class='item'></td><td type='"+$type+"' id='"+$id+"'>"+$cantidad+"</td><td>"+$condicion+"</td></tr>");
	
}

function _fSuccess( msg ){

	html = '<div class="messages"><ul class="success-msg"><li>'+msg+'</li></ul></div>';
	
	$("#sidebar").prepend( html );
	
	setTimeout( function(){
		
		$("#sidebar .messages").fadeOut( 'slow', function(){
			$(this).remove();
		} );
	
	},1500);
	
}

function _fError( msg ){

	html = '<div class="messages"><ul class="error-msg"><li>'+msg+'</li></ul></div>';
	
	$("#sidebar").prepend( html );
	
	setTimeout( function(){
		
		$("#sidebar .messages").fadeOut( 'slow', function(){
			$(this).remove();
		} );
	
	},1500);
	
}

function _t(key) {
    var result = stringLibrary;
    key = key.split(".");

    for ( var i in key ) {
        if ( result[ key[i] ] ) {
            result = result[ key[i] ];
        } else {
            return null;
        }
    }

    return result;
}

function bindEnter($function, $params ){
	
	var $p = $params;
	var $keycode;
	
	f = function(e) {
		
		if (window.event){ 
			var $keycode = window.event.keyCode; //ie
		}else if (e.keyCode){
			$keycode = e.keyCode; //ff
		}else{
			$keycode = e.which; 
		}
		
		if ($keycode == 13) {
	    	$function( $p );
	    	return false; 
	    }
	}
	
	if( $.browser.msie ){
		
		$(document.body).unbind('keydown');
		$(document.body).keydown( f );
		
	} else {
		
		$(window).unbind('keydown');
		$(window).keydown( f );
	}
	
} 



function bindFormEnter( $id ){
	
	var send = function(){
		$("#" + $id).submit()
	};
	
	$("#" + $id + " .submit-group a").click( send );
	
	bindEnter(send);
}

jQuery.fn.reset = function () {
  $(this).each (function() { this.reset(); });
}

function bindOrderList(){
	
//	$(".tablesorter tbody tr").hover(
//		function(){
//			$(this).css("cursor", "pointer");
//			$("td", $(this)).css("background-color", "#fff");
//			$("td, td a", $(this)).css("color", "#C1272D");
//		},
//		function(){
//			
//			if( $(this).hasClass("order-status-1") ){
//		
//				$color = "#FFFFFF";
//				$backgroundcolor = "#F17E78";
//		
//			} else if( $(this).hasClass("order-status-2") ){
//				$color = "#FFFFFF";
//				$backgroundcolor = "#F8AB56";
//				
//			} else if( $(this).hasClass("order-status-3") ){
//				$color = "#FFFFFF";
//				$backgroundcolor = "#54C4BC";
//				
//			} else{
//				$color = "#FFFFFF";
//				$backgroundcolor = "#D5D6D7";
//			}
//			
//			$("td", $(this)).css("background-color", null);
//			$("td, td a", $(this)).css("color", null);
//		}
//	);

	$(".tablesorter tbody tr").click(
		function(){
			location.href = $("td:first a", $(this)).attr("href");
		}
	);
}

function bindKeyPress($key, $function, $params ){
	
	var $codes = new Array();
	
	
	var $p = $params;
	var $keycode;
	
	f = function(e) {
		
		if (window.event){ 
			var $keycode = window.event.keyCode; //ie
		}else if (e.keyCode){
			$keycode = e.keyCode; //ff
		}else{
			$keycode = e.which; 
		}
		
//		console.log( $keycode );
//		console.log( $key );
		
		if ($keycode == $key ) {
			
			if( $params!= null ){
				$function( $p );
			} else {
				$function();
			}
	    	
	    	return false; 
	    }
	}
	
	if( $.browser.msie ){
		
		$(document.body).unbind('keydown');
		$(document.body).keydown( f );
		
	} else {
		
		$(window).unbind('keydown');
		$(window).keydown( f );
	}
	
}

function bindCategoriesOrder( $url ){
	
	$("#ordenCategorias").bind('click.init', function(e){
		
		$.ajax({
			  url: $url,
			  type: 'GET',
			  success: function( html ) {
				  
				  $__boxy = new Boxy(html, {
					  	title: _t("categoriesOrder"),
						modal: false,
						closeable: true,
						unloadOnHide : false,
						afterHide: setCategoriesOrder
				  });
				  
				  popupMaxHeight(".boxy-inner #categoriesOrder");
				  
				  $__boxy.center();
				  $( "#sortable" ).sortable();	
				  
				  $(".boxy-inner #categoriesOrder .button").click( function(){
					  setCategoriesOrder();
					  $__boxy.hide();
				  });
				  
			  }		  
			});
		
		
		$("#ordenCategorias").unbind('click.init');
		
		$("#ordenCategorias").click(function(){
			$__boxy.show();
		});
		
		return false;
	});
}

function setCategoriesOrder(){
	
	var $ids = new Array()
	
	$(".boxy-inner #categoriesOrder li").each(function(i){
		
		$ids[i] = $(this).attr('id').split("-")[1];
		
	});
	
	$("#ordenCategorias").val( $ids.join(","));
}
	
function popupMaxHeight( $selector ){

	$boxHeight = $( $selector ).height();
	$winHeight = $(window).height();
	$maxHeight = $winHeight - 100;
	
	if ( $boxHeight >= $maxHeight ){
		  $( $selector ).css('height', $maxHeight).css('overflow-y', 'scroll');
	}
}



















